import dht
from lib.clock import custom_timer
from machine import Pin
from lib.config.index import sensor_config

temp = -1
humidity = -1
dht11 = None

dht_config = sensor_config.get_sensor("dht11")
dht_pin = dht_config["pin"]
print("dht pin:", dht_pin)


def readDHT11(pin):
    global temp, humidity, dht11
    if not dht11:
        dht11 = dht.DHT11(Pin(pin, Pin.IN))
    try:
        dht11.measure()
        temp = dht11.temperature()
        humidity = dht11.humidity()
        return (temp, humidity)
    except Exception as e:
        print("dht11 error:", e)


def printDHT11():
    print(f"Temperature : {temp:.1f}°C")
    print(f"Humidity    : {humidity:.1f}%")


def demo():
    timer = custom_timer.CustomTimer(2)
    while True:
        if timer.check():
            readDHT11(dht_pin)
            printDHT11()


if __name__ == "__main__":
    demo()
